/**
 * @file 工作台页面
 * @author wangshaozhi(wangshaozhi@baidu.com)
 */

import {useCallback, useEffect, useMemo, useRef} from "react";
import {observer} from "mobx-react";
import {Button, Modal, Table, message} from 'antd';
import {useHistory} from "react-router-dom";
import request from '../../../request';

// store
import {MainStore} from "../../../store/mainStore";

// constants
import {ARTICLE_LIST_URL, DELETE_ARTICLE_URL} from "../../../request/url";

// style
import cls from './index.module.scss';
interface IProps {
    store: MainStore;
}

export const Workbench: React.FC<IProps> = observer(({
    store
}) => {
    const {
        articleStore,
        sideBarStore
    } = store;
    const getArticleListRef = useRef<boolean>(true);
    const history = useHistory();

    const getArticleList = useCallback(async () => {
        try {
            const author = JSON.parse(localStorage.getItem('user') || '{}').username;
            const res = await request({
                method: 'post',
                url: ARTICLE_LIST_URL,
                data: {
                    author
                }
            });
            articleStore.update({
                articleList: res.data
            });
        }
        catch (e) {

        }
    }, [articleStore])

    useEffect(() => {
        if (getArticleListRef.current) {
            getArticleList();
            getArticleListRef.current = false;
        }
    }, [articleStore, getArticleList, store]);

    const onEditHandler = useCallback((id: number) => {
        sideBarStore.update({
            currSelectedKeys: ['add', 'article'],
            currOpenKeys: ['article']
        })
        history.push(`/article/add/?id=${id}`);
    }, [history, sideBarStore]);

    const onDeleteHandler = useCallback((id: number) => {
        const deleteHandler = async () => {
            try {
                const res = await request({
                    method: 'post',
                    url: DELETE_ARTICLE_URL,
                    data: {
                        id
                    }
                });
                const {
                    code,
                    msg
                } = res.data;
                if (code === 0) {
                    message.success(msg);
                    getArticleList();
                    return;
                }
                message.error(msg);
            }
            catch(e) {
                message.error('删除失败');
            }
        }
        Modal.confirm({
            title: '确认要删除吗？',
            content: '删除后文章内容将不会恢复',
            okText: '确认',
            cancelText: '取消',
            onOk: deleteHandler
        })
    }, [getArticleList]);

    const columns = useMemo(() => ([
        {
            dataIndex: 'id',
            title: 'id'
        },
        {
            dataIndex: 'title',
            title: '标题'
        },
        {
            dataIndex: 'introduction',
            title: '简介'
        },
        {
            dataIndex: 'publishTime',
            title: '发布时间'
        },
        {
            dataIndex: 'typeName',
            title: '类型'
        },
        {
            dataIndex: 'viewsCount',
            title: '阅读数量'
        },
        {
            dataIndex: 'action',
            title: '操作',
            render: (_: any, record: any) => (
                <div className={cls.btnWrapper}>
                    <Button
                        size="small"
                        type="primary"
                        className={cls.editBtn}
                        onClick={() => onEditHandler(record.id)}
                    >
                        修改
                    </Button>
                    <Button
                        danger
                        size="small"
                        onClick={() => onDeleteHandler(record.id)}
                    >
                        删除
                    </Button>
                </div>
            )
        }
    ]), [onDeleteHandler, onEditHandler]);

    return (
        <div className={cls.wrapper}>
            <Table
                columns={columns}
                rowKey={item => item.id}
                dataSource={articleStore.articleList}
                pagination={{
                    pageSize: 8
                }}
            />
        </div>
    );
});